package com.quectel.multicamera;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Switch;

import androidx.appcompat.app.AppCompatActivity;

import com.quectel.multicamera.utils.GUtilMain;
import com.quectel.multicamera.utils.PreviewParams;
import com.quectel.multicamera.utils.RecorderParams;
import com.quectel.qcarapi.QCarVersion;
import com.quectel.qcarapi.util.QCarLog;

import java.util.ArrayList;
import java.util.List;


public class SetActivity extends AppCompatActivity {

    private String TAG = "SetActivity";
    private Spinner preResolutionSpinner;
    private Spinner videoResolutionSpinner;
    private Spinner preNumSpinner;
    private Spinner csiNumSpinner;

    //Video encoder
    private Spinner recorderNumSpinner;
    private Spinner childRecorderSizeSpinner;
    private Spinner recorderSSP;  //分段大小选项
    private Spinner codecSpinner; //编码格式选项
    private Spinner containerSpinner; //录像格式
    private Spinner mainstreamerSpinner; //主码率
    private Spinner substreamerSpinner; //次码率

    private Switch switch_cr; //是否开启录像子码流
    private Switch switch_audio; //是否开启录像音频

    /**************************四合一录制参数配置****************************/
    private Spinner csiNumMergeSpinner;
    private Spinner recorderResolutionMergeSpinner;
    private Spinner recorderSMergeSPinner;  //分段大小选项
    private Spinner codecMergeSpinner; //编码格式选项
    private Spinner containerMergeSpinner; //录像格式
    private Spinner bitrateMergeSpinner; //主码率
    private Switch audioMergeSw; //是否开启录像音频
    private Switch subMergeSwitch;
    private Spinner subSizeMergeSpinner;
    /**************************四合一录制参数配置****************************/

    private Switch debugEnableSwitch;

    private int size1 = 2;
    private int size2 = 2;

    private List<Integer> noList;
    private ArrayAdapter<Integer> noAdapter;

    private RecorderParams rParams = GUtilMain.getRecorderParams();
    private static RecorderParams rMParams = GUtilMain.getMergeRecorderParams();
    private PreviewParams pParams = GUtilMain.getPreviewParams();

    static {
        System.loadLibrary("mmqcar_qcar_jni");
        if (Build.VERSION.SDK_INT == 28) {
            GUtilMain.MEDIA_OUTPUT_FORMAT_TS = 4;
        } else if (Build.VERSION.SDK_INT == 25) {
            GUtilMain.MEDIA_OUTPUT_FORMAT_TS = 2;
        }

        //init data
        rMParams.setCsiNum(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String sdkVersion = QCarVersion.qcarGetVersion(); // query the sdk version number
        QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "sdkVersion = " + sdkVersion);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_set);
        preResolutionSpinner = (Spinner) findViewById(R.id.spinner1);
        videoResolutionSpinner = (Spinner) findViewById(R.id.spinner2);
        preNumSpinner = (Spinner) findViewById(R.id.spinner3);
        csiNumSpinner = (Spinner) findViewById(R.id.csiNumSpinner);

        debugEnableSwitch = (Switch) findViewById(R.id.global_debug_switch);

        noList = new ArrayList<>();

        csiNumSpinner.setSelection(pParams.getCsiNum());

        /********************** Mdvx Read Test: START ********************************/
        /*long pMdvxReadObj = QCarMdvxRead.create();
        byte[] outBuf = new byte[1024*1024*4];  // 4M
        boolean needIframe = true;
        int count = 0;
        String path = "/storage/emulated/0/recorder20191230154019.mdvx";

        File file1 =new File("/storage/emulated/0/video1.h264");
        FileOutputStream fos1 = null;
        if(!file1.exists()){
            try {
                file1.createNewFile();
                fos1 = new FileOutputStream(file1);
            }catch(Exception e){

            }
        }

        int rc = QCarMdvxRead.open(pMdvxReadObj, path);
        if(rc == 0){
            Log.e(TAG, "Open mdvx success");
        }else{
            Log.e(TAG, "Open mdvx failed");
        }

        rc = QCarMdvxRead.seek(pMdvxReadObj,1,1577692203600000L);
        if(rc == 0){
            Log.e(TAG,"Seek success");
        }else{
            Log.e(TAG,"Seek failed, rc = "+rc);
        }

        while(true) {
            QCarMdvxRead.FrameInfo frameInformation = QCarMdvxRead.readFrame(pMdvxReadObj,outBuf);
            if(frameInformation == null){
                Log.e(TAG,"mdvx read frame failed");
                break;
            }else {
                //Log.e(TAG, "frameInfo.channel = " + frameInformation.channel + ", frameInfo.frameType = " + frameInformation.frameType +
                //        ", frameInfo.frameLen = " + frameInformation.frameLen + ", frameInfo.framePts = " + frameInformation.framePts);
                if (needIframe && frameInformation.frameType == QCarMdvxRead.DVR_FRAME_TYPE_H264P) {
                    Log.e(TAG, "need Iframe");
                }

                if (frameInformation.frameType == QCarMdvxRead.DVR_FRAME_TYPE_H264I) {
                    needIframe = false;
                }

                if(frameInformation.channel == 1 && (frameInformation.frameType == QCarMdvxRead.DVR_FRAME_TYPE_H264P ||
                        frameInformation.frameType == QCarMdvxRead.DVR_FRAME_TYPE_H264I)){
                    Log.e(TAG, " ++++++++ frameInfo.channel = " + frameInformation.channel + ", frameInfo.frameType = " + frameInformation.frameType +
                            ", frameInfo.frameLen = " + frameInformation.frameLen + ", frameInfo.framePts = " + frameInformation.framePts);

                    try {
                        fos1.write(outBuf,0,frameInformation.frameLen);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                count++;
            }
        }


        try {
            fos1.close();
        }catch(Exception e){

        }*/

        /********************** Mdvx Read Test: END ********************************/

        csiNumSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                pParams.setCsiNum(position);
                rParams.setCsiNum(position);
                rParams.setRecorderNums(4); //恢复默认设置
                setPreviewVideoByCsiNum(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        preResolutionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "选择了="+position);
                pParams.setPsPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        videoResolutionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "选择了="+position);
                rParams.setVsPosition(position);
                rParams.adjustResolutionWidthReValue(parent.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        preNumSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "选择了="+position);
                pParams.setPreviewNum(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        debugEnableSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                    case R.id.global_debug_switch:
                        if (isChecked)
                        {
                            QCarLog.setTagLogLevel(Log.DEBUG);
                        } else {
                            QCarLog.setTagLogLevel(Log.INFO);
                        }
                }
            }
        });

        // Video encoder
        recorderNumSpinner = (Spinner) findViewById(R.id.spinner4);
        childRecorderSizeSpinner = (Spinner) findViewById(R.id.child_spinner);
        codecSpinner = (Spinner) findViewById(R.id.codecSpinner);
        containerSpinner = (Spinner) findViewById(R.id.containerSpinner);
        recorderSSP = (Spinner) findViewById(R.id.recorderSSpinner);
        mainstreamerSpinner = (Spinner) findViewById(R.id.mainkps); //主码率
        substreamerSpinner = (Spinner) findViewById(R.id.subkps);   //次码率
        switch_cr = (Switch) findViewById(R.id.switch_1);
        switch_audio = (Switch) findViewById(R.id.audiosw);

        switch_cr.setChecked(rParams.isChildRecordEnable());
        switch_audio.setChecked(rParams.isAudioRecordEnable());
        childRecorderSizeSpinner.setSelection(rParams.getChild_size());
        recorderSSP.setSelection(rParams.getSegmentSizePosition());
        mainstreamerSpinner.setSelection(rParams.getMainRatePosition());
        substreamerSpinner.setSelection(rParams.getSubRatePosition());
        codecSpinner.setSelection(rParams.getCodecTypePosition());
        containerSpinner.setSelection(rParams.getCtPosition());

        recorderNumSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "选择了="+position);
                rParams.setRecorderNums(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        childRecorderSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rParams.setChild_size(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        recorderSSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rParams.setSegmentSizePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mainstreamerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rParams.setMainRatePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        substreamerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rParams.setSubRatePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        codecSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rParams.setCodecTypePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        switch_cr.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                    case R.id.switch_1:
                        if (isChecked)
                        {
                            rParams.setChildRecordEnable(true);
                        } else {
                            rParams.setChildRecordEnable(false);
                        }
                }
            }
        });
        switch_audio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                    case R.id.audiosw:
                        if (isChecked)
                        {
                            rParams.setAudioRecordEnable(true);
                        } else {
                            rParams.setAudioRecordEnable(false);
                        }
                }
            }
        });

        containerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rParams.setCtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        csiNumMergeSpinner = (Spinner) findViewById(R.id.csiNumMergeSpinner);
        recorderResolutionMergeSpinner = (Spinner) findViewById(R.id.recorderResolutionMergeSpinner);
        recorderSMergeSPinner = (Spinner) findViewById(R.id.recorderSMergeSpinner);
        codecMergeSpinner = (Spinner) findViewById(R.id.codecMergeSpinner);
        containerMergeSpinner = (Spinner) findViewById(R.id.containerMergeSpinner);
        bitrateMergeSpinner = (Spinner) findViewById(R.id.bitrateMergeSpinner);
        audioMergeSw = (Switch) findViewById(R.id.audioMergeSw);
        subMergeSwitch = (Switch) findViewById(R.id.subMergeSwitch);
        subSizeMergeSpinner = (Spinner) findViewById(R.id.subSizeMergeSpinner);

        csiNumMergeSpinner.setSelection(rMParams.getCsiNum());
        recorderResolutionMergeSpinner.setSelection(rMParams.getVsPosition());
        recorderSMergeSPinner.setSelection(rMParams.getSegmentSizePosition());
        codecMergeSpinner.setSelection(rMParams.getCodecTypePosition());
        containerMergeSpinner.setSelection(rMParams.getCtPosition());
        bitrateMergeSpinner.setSelection(rMParams.getMainRatePosition());
        audioMergeSw.setChecked(rMParams.isAudioRecordEnable());
        subMergeSwitch.setChecked(rMParams.isChildRecordEnable());
        subSizeMergeSpinner.setSelection(rMParams.getChild_size());

        csiNumMergeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setCsiNum(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        recorderResolutionMergeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setVsPosition(position);
                rMParams.adjustResolutionWidthReValue(parent.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        recorderSMergeSPinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setSegmentSizePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        codecMergeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setCodecTypePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        containerMergeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setCtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        bitrateMergeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setMainRatePosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        audioMergeSw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                    case R.id.audioMergeSw:
                        if (isChecked)
                        {
                            rMParams.setAudioRecordEnable(true);
                        } else {
                            rMParams.setAudioRecordEnable(false);
                        }
                }
            }
        });

        subMergeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                    case R.id.subMergeSwitch:
                        if (isChecked)
                        {
                            rMParams.setChildRecordEnable(true);
                        } else {
                            rMParams.setChildRecordEnable(false);
                        }
                }
            }
        });

        subSizeMergeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rMParams.setChild_size(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        GUtilMain.setqContext(getApplicationContext());
    }

    private void setPreviewVideoByCsiNum(int csiNum) {
        ArrayAdapter<String> resolutionAdapter;
        List<String> resolutionList = new ArrayList<>();
        noList.clear();
        for (int i = 0; i <= 4; i++) {
            noList.add(i);
        }
        if (csiNum == 1) {
            resolutionList.add("1080p");
        } else if (csiNum == 2){
            for (int i = 5; i <= 8; i++) {
                noList.add(i);
            }
        }
        resolutionList.add("720p");
        resolutionList.add("480p");

        noAdapter = new ArrayAdapter<Integer>(this, R.layout.support_simple_spinner_dropdown_item, noList);
        resolutionAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, resolutionList);

        preResolutionSpinner.setAdapter(resolutionAdapter);
        videoResolutionSpinner.setAdapter(resolutionAdapter);
        preNumSpinner.setAdapter(noAdapter);
        recorderNumSpinner.setAdapter(noAdapter);

        QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "pParams.getPreviewNum = " + pParams.getPreviewNum() + preNumSpinner.getAdapter().getCount());
        QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "recorderNumSpinner.getRecorderNums = " + rParams.getRecorderNums() + recorderNumSpinner.getAdapter().getCount());
        QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "pParams.getPsPosition() = " + pParams.getPsPosition() + preResolutionSpinner.getAdapter().getCount());
        QCarLog.i(QCarLog.LOG_MODULE_APP, TAG, "rParams.getVsPosition() = " + rParams.getVsPosition() + videoResolutionSpinner.getAdapter().getCount());
        preNumSpinner.setSelection(pParams.getPreviewNum());
        recorderNumSpinner.setSelection(rParams.getRecorderNums());
        preResolutionSpinner.setSelection(pParams.getPsPosition());
        videoResolutionSpinner.setSelection(rParams.getVsPosition());
    }

    private void adaptResoultionList(int csiNum) {
        ArrayAdapter<String> resolutionAdapter;
        List<String> resolutionList = new ArrayList<>();
        if (csiNum == 1) {
            resolutionList.add("1080p");
        }
        resolutionList.add("720p");
        resolutionList.add("480p");

        resolutionAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, resolutionList);
        recorderResolutionMergeSpinner.setAdapter(resolutionAdapter);
        recorderResolutionMergeSpinner.setSelection(rMParams.getVsPosition());
    }

    public void start(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("size1",size1);
        intent.putExtra("size2",size2);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }
}
